﻿using Microsoft.Extensions.DependencyInjection;
using MQTTnet.Server;
using SBlogCore.MqttService.Proxy;
using MQTTnet;
using SBlogCore.Common.DispatchProxyIn;
using SBlogCore.Common.App.Manager;

namespace SBlogCore.MqttService.Extenions
{
    public static class MqttServiceSetUp
    {
        public static IServiceCollection AddMqttServiceSetUp(this IServiceCollection services)
        {
            services.AddSingleton<MqttServer>(_ =>
            {
                string port = AppSetting.ReadAppSettings("MQTT:Port");
                string maxCount = AppSetting.ReadAppSettings("MQTT:MaxCount");
                MqttServerOptionsBuilder optionsBuilder = new MqttServerOptionsBuilder();
                optionsBuilder.WithDefaultEndpoint();

                optionsBuilder.WithDefaultEndpointPort(int.Parse(port??"5692")); // 设置 服务端 端口号
                if (string.IsNullOrEmpty(maxCount))
                {
                    optionsBuilder.WithConnectionBacklog(int.Parse(maxCount)); // 最大连接数
                }
                MqttServerOptions options = optionsBuilder.Build();

                var serve = new MqttFactory().CreateMqttServer(options);
                return serve;
            });
            services.AddHostedService<MqttHostService>();
            services.AddSingleton<IMqttServerEvents, MqttServerEvents>();
            services.AddDispatchProxyService<IMqttDispatchProxy, MqttDispatchProxy>();
            return services;
        }
    }
}
